{% extends 'base.html' %}

{% block title %}标签打印配置{% endblock %}

{% block extra_css %}
{% load static %}
<link rel="stylesheet" href="{% static 'css/label-ui.css' %}">
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
            <li class="breadcrumb-item"><a href="{% url 'assets:asset_list' %}">资产管理</a></li>
            <li class="breadcrumb-item active">标签打印配置</li>
        </ol>
    </nav>

    <div class="row">
        <!-- 配置选项 -->
        <div class="col-md-8">
            <div class="config-card">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h4 class="mb-0">
                        <i class="fas fa-cog text-primary me-2"></i>
                        标签打印配置
                    </h4>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-info btn-sm dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="fas fa-template me-1"></i>使用模板
                        </button>
                        <ul class="dropdown-menu">
                            <li><h6 class="dropdown-header">我的模板</h6></li>
                            {% for template in user_templates %}
                                <li><a class="dropdown-item load-template-btn" href="#" data-template-id="{{ template.id }}">
                                    {{ template.name }}
                                    {% if template.is_default %}<span class="badge bg-success ms-1">默认</span>{% endif %}
                                </a></li>
                            {% empty %}
                                <li><span class="dropdown-item-text text-muted">暂无模板</span></li>
                            {% endfor %}
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{% url 'assets:label_template_create' %}">
                                <i class="fas fa-plus me-2"></i>新建模板
                            </a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:label_template_list' %}">
                                <i class="fas fa-list me-2"></i>管理模板
                            </a></li>
                        </ul>
                    </div>
                </div>
                
                <form method="post" id="print-config-form">
                    {% csrf_token %}
                    
                    <!-- 隐藏字段：资产ID -->
                    {% if asset %}
                        <input type="hidden" name="asset_id" value="{{ asset.id }}">
                    {% else %}
                        <input type="hidden" name="asset_ids" value="{{ asset_ids }}">
                    {% endif %}
                    
                    <!-- 标签尺寸选择 -->
                    <div class="mb-4">
                        <h5 class="mb-3">
                            <i class="fas fa-ruler me-2"></i>
                            标签尺寸
                        </h5>
                        
                        <div class="size-option" data-size="small">
                            <input type="radio" name="label_size" value="small" id="size-small">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">小标签</h6>
                                    <small class="text-muted">50×25mm - 适合小型设备</small>
                                </div>
                                <div class="text-end">
                                    <span class="badge bg-info">节省纸张</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="size-option selected" data-size="medium">
                            <input type="radio" name="label_size" value="medium" id="size-medium" checked>
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">中标签</h6>
                                    <small class="text-muted">70×40mm - 标准推荐尺寸</small>
                                </div>
                                <div class="text-end">
                                    <span class="badge bg-success">推荐</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="size-option" data-size="large">
                            <input type="radio" name="label_size" value="large" id="size-large">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">大标签</h6>
                                    <small class="text-muted">90×50mm - 适合大型设备</small>
                                </div>
                                <div class="text-end">
                                    <span class="badge bg-warning">详细信息</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 页面布局选择 -->
                    {% if not asset %}
                    <div class="mb-4">
                        <h5 class="mb-3">
                            <i class="fas fa-th me-2"></i>
                            页面布局
                        </h5>
                        
                        <div class="layout-grid">
                            <div class="layout-option" data-layout="6">
                                <input type="radio" name="labels_per_page" value="6" id="layout-6">
                                <i class="fas fa-th-large fa-2x mb-2"></i>
                                <h6>6个/页</h6>
                                <small class="text-muted">2×3 布局</small>
                            </div>
                            
                            <div class="layout-option selected" data-layout="12">
                                <input type="radio" name="labels_per_page" value="12" id="layout-12" checked>
                                <i class="fas fa-th fa-2x mb-2"></i>
                                <h6>12个/页</h6>
                                <small class="text-muted">3×4 布局</small>
                            </div>
                            
                            <div class="layout-option" data-layout="24">
                                <input type="radio" name="labels_per_page" value="24" id="layout-24">
                                <i class="fas fa-border-all fa-2x mb-2"></i>
                                <h6>24个/页</h6>
                                <small class="text-muted">4×6 布局</small>
                            </div>
                        </div>
                    </div>
                    {% endif %}
                    
                    <!-- 内容选项 -->
                    <div class="mb-4">
                        <h5 class="mb-3">
                            <i class="fas fa-list-check me-2"></i>
                            标签内容
                        </h5>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="include_qr" id="include-qr" checked>
                                    <label class="form-check-label" for="include-qr">
                                        <i class="fas fa-qrcode me-2"></i>
                                        包含二维码
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="include_category" id="include-category" checked>
                                    <label class="form-check-label" for="include-category">
                                        <i class="fas fa-tags me-2"></i>
                                        显示资产类别
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="include_department" id="include-department" checked>
                                    <label class="form-check-label" for="include-department">
                                        <i class="fas fa-building me-2"></i>
                                        显示所属部门
                                    </label>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="include_user" id="include-user" checked>
                                    <label class="form-check-label" for="include-user">
                                        <i class="fas fa-user me-2"></i>
                                        显示使用人
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="include_date" id="include-date" checked>
                                    <label class="form-check-label" for="include-date">
                                        <i class="fas fa-calendar me-2"></i>
                                        显示启用日期
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="include_timestamp" id="include-timestamp" checked>
                                    <label class="form-check-label" for="include-timestamp">
                                        <i class="fas fa-clock me-2"></i>
                                        显示打印时间
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 自定义标题 -->
                    <div class="mb-4">
                        <h5 class="mb-3">
                            <i class="fas fa-edit me-2"></i>
                            自定义选项
                        </h5>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">标签标题前缀：</label>
                                <input type="text" class="form-control" name="title_prefix" 
                                       placeholder="例如：公司名称" maxlength="20">
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">标签底部备注：</label>
                                <input type="text" class="form-control" name="footer_note" 
                                       placeholder="例如：如有遗失请联系..." maxlength="30">
                            </div>
                        </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="d-flex justify-content-between">
                        <div>
                            <button type="button" class="btn btn-outline-info btn-custom" id="save-template-btn">
                                <i class="fas fa-save me-2"></i>保存为模板
                            </button>
                        </div>
                        <div>
                            <a href="{% if asset %}{% url 'assets:asset_detail' asset.pk %}{% else %}{% url 'assets:asset_batch_print_labels' %}{% endif %}" 
                               class="btn btn-outline-secondary btn-custom me-2">
                                <i class="fas fa-arrow-left me-2"></i>返回
                            </a>
                            <button type="button" class="btn btn-info btn-custom me-2" id="preview-btn">
                                <i class="fas fa-eye me-2"></i>预览
                            </button>
                            <button type="submit" class="btn btn-success btn-custom">
                                <i class="fas fa-print me-2"></i>生成标签
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 预览和信息 -->
        <div class="col-md-4">
            <!-- 标签预览 -->
            <div class="preview-card">
                <h5 class="mb-3">
                    <i class="fas fa-eye text-white me-2"></i>
                    标签预览
                </h5>
                
                <div class="label-preview" id="label-preview">
                    <div class="preview-content">
                        <div class="label-title">
                            {% if asset %}{{ asset.name|truncatechars:20 }}{% else %}示例资产名称{% endif %}
                        </div>
                        <div class="label-subtitle">
                            编号: {% if asset %}{{ asset.asset_number }}{% else %}AS001{% endif %}
                        </div>
                        <div class="label-meta">
                            类别: {% if asset %}{{ asset.category.name|default:"未分类" }}{% else %}电脑设备{% endif %}
                        </div>
                        <div class="label-meta">
                            部门: {% if asset %}{{ asset.department.name|default:"未分配" }}{% else %}IT部门{% endif %}
                        </div>
                        <div class="label-timestamp">
                            打印: 2024-01-01 10:00
                        </div>
                    </div>
                    <div class="label-qr" id="qr-preview">
                        二维码
                    </div>
                </div>
                
                <small class="text-white-50">
                    * 实际标签可能与预览略有差异
                </small>
            </div>
            
            <!-- 资产信息摘要 -->
            {% if asset %}
            <div class="config-card">
                <h5 class="mb-3">
                    <i class="fas fa-info-circle text-primary me-2"></i>
                    资产信息
                </h5>
                
                <div class="asset-summary">
                    <h6>{{ asset.name }}</h6>
                    <p class="mb-2">
                        <strong>编号：</strong>{{ asset.asset_number }}<br>
                        <strong>类别：</strong>{{ asset.category.name|default:"未分类" }}<br>
                        <strong>部门：</strong>{{ asset.department.name|default:"未分配" }}<br>
                        {% if asset.user %}
                        <strong>使用人：</strong>{{ asset.user.get_full_name|default:asset.user.username }}<br>
                        {% endif %}
                        <strong>状态：</strong>{{ asset.get_status_display }}
                    </p>
                </div>
            </div>
            {% else %}
            <div class="config-card">
                <h5 class="mb-3">
                    <i class="fas fa-info-circle text-primary me-2"></i>
                    批量打印信息
                </h5>
                
                <div class="asset-summary">
                    <p><strong>选中资产数量：</strong>{{ asset_count }} 个</p>
                    <p><strong>预计页数：</strong><span id="estimated-pages">1</span> 页</p>
                    <p><strong>建议标签尺寸：</strong>中标签 (70×40mm)</p>
                </div>
            </div>
            {% endif %}
            
            <!-- 打印提示 -->
            <div class="config-card">
                <h6 class="mb-3">
                    <i class="fas fa-lightbulb text-warning me-2"></i>
                    打印提示
                </h6>
                
                <ul class="list-unstyled small">
                    <li class="mb-2">
                        <i class="fas fa-check text-success me-2"></i>
                        建议使用激光打印机获得最佳效果
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check text-success me-2"></i>
                        使用不干胶标签纸，便于粘贴
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check text-success me-2"></i>
                        打印前请检查打印机设置
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check text-success me-2"></i>
                        二维码需要足够清晰才能扫描
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- 保存模板模态框 -->
<div class="modal fade" id="saveTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">保存为标签模板</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="save-template-form">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">模板名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="template_name" required maxlength="100">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">模板描述</label>
                        <textarea class="form-control" name="template_description" rows="3" maxlength="500"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_public" id="template-is-public">
                            <label class="form-check-label" for="template-is-public">
                                设为公共模板（其他用户可使用）
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_default" id="template-is-default">
                            <label class="form-check-label" for="template-is-default">
                                设为我的默认模板
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>保存模板
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 尺寸选择
    const sizeOptions = document.querySelectorAll('.size-option');
    sizeOptions.forEach(option => {
        option.addEventListener('click', function() {
            sizeOptions.forEach(opt => opt.classList.remove('selected'));
            this.classList.add('selected');
            this.querySelector('input[type="radio"]').checked = true;
            updatePreview();
        });
    });
    
    // 布局选择
    const layoutOptions = document.querySelectorAll('.layout-option');
    layoutOptions.forEach(option => {
        option.addEventListener('click', function() {
            layoutOptions.forEach(opt => opt.classList.remove('selected'));
            this.classList.add('selected');
            this.querySelector('input[type="radio"]').checked = true;
            updateEstimatedPages();
        });
    });
    
    // 内容选项变化
    const contentOptions = document.querySelectorAll('input[type="checkbox"]');
    contentOptions.forEach(option => {
        option.addEventListener('change', updatePreview);
    });
    
    // 更新预览
    function updatePreview() {
        const includeQr = document.getElementById('include-qr').checked;
        const qrPreview = document.getElementById('qr-preview');
        
        if (includeQr) {
            qrPreview.style.display = 'flex';
        } else {
            qrPreview.style.display = 'none';
        }
        
        // 根据选择的尺寸调整预览大小
        const selectedSize = document.querySelector('input[name="label_size"]:checked').value;
        const labelPreview = document.getElementById('label-preview');
        
        switch(selectedSize) {
            case 'small':
                labelPreview.style.minHeight = '80px';
                labelPreview.style.fontSize = '10px';
                break;
            case 'large':
                labelPreview.style.minHeight = '160px';
                labelPreview.style.fontSize = '14px';
                break;
            default: // medium
                labelPreview.style.minHeight = '120px';
                labelPreview.style.fontSize = '12px';
        }
    }
    
    // 更新预计页数
    function updateEstimatedPages() {
        const labelsPerPage = parseInt(document.querySelector('input[name="labels_per_page"]:checked')?.value || 12);
        const assetCount = parseInt("{{ asset_count|default:1 }}", 10);
        const estimatedPages = Math.ceil(assetCount / labelsPerPage);
        
        const pagesSpan = document.getElementById('estimated-pages');
        if (pagesSpan) {
            pagesSpan.textContent = estimatedPages;
        }
    }
    
    // 预览按钮
    document.getElementById('preview-btn').addEventListener('click', function() {
        // 这里可以实现预览功能，比如打开新窗口显示预览
        alert('预览功能开发中...');
    });
    
    // 加载模板配置
    document.querySelectorAll('.load-template-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const templateId = this.dataset.templateId;
            loadTemplate(templateId);
        });
    });
    
    // 保存模板按钮
    document.getElementById('save-template-btn').addEventListener('click', function() {
        const modal = new bootstrap.Modal(document.getElementById('saveTemplateModal'));
        modal.show();
    });
    
    // 保存模板表单提交
    document.getElementById('save-template-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveTemplate();
    });
    
    // 加载模板配置
    function loadTemplate(templateId) {
        fetch(`/assets/label-template/${templateId}/config/`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const config = data.config;
                    
                    // 设置表单值
                    document.querySelector(`input[name="label_size"][value="${config.size}"]`).checked = true;
                    document.querySelector(`input[name="labels_per_page"][value="${config.labels_per_page}"]`).checked = true;
                    
                    document.getElementById('include-qr').checked = config.include_qr;
                    document.getElementById('include-category').checked = config.include_category;
                    document.getElementById('include-department').checked = config.include_department;
                    document.getElementById('include-user').checked = config.include_user;
                    document.getElementById('include-date').checked = config.include_date;
                    document.getElementById('include-timestamp').checked = config.include_timestamp;
                    
                    document.querySelector('input[name="title_prefix"]').value = config.title_prefix || '';
                    document.querySelector('input[name="footer_note"]').value = config.footer_note || '';
                    
                    // 更新UI
                    updateSizeSelection();
                    updateLayoutSelection();
                    updatePreview();
                    updateEstimatedPages();
                    
                    // 显示成功消息
                    showMessage('success', `已加载模板: ${data.template.name}`);
                } else {
                    showMessage('error', data.error || '加载模板失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('error', '加载模板时发生错误');
            });
    }
    
    // 保存模板
    function saveTemplate() {
        const formData = new FormData();
        formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);
        formData.append('name', document.querySelector('input[name="template_name"]').value);
        formData.append('description', document.querySelector('textarea[name="template_description"]').value);
        formData.append('is_public', document.getElementById('template-is-public').checked ? 'on' : '');
        formData.append('is_default', document.getElementById('template-is-default').checked ? 'on' : '');
        
        // 添加当前配置
        formData.append('label_size', document.querySelector('input[name="label_size"]:checked').value);
        formData.append('labels_per_page', document.querySelector('input[name="labels_per_page"]:checked')?.value || '12');
        formData.append('include_qr', document.getElementById('include-qr').checked ? 'on' : '');
        formData.append('include_category', document.getElementById('include-category').checked ? 'on' : '');
        formData.append('include_department', document.getElementById('include-department').checked ? 'on' : '');
        formData.append('include_user', document.getElementById('include-user').checked ? 'on' : '');
        formData.append('include_date', document.getElementById('include-date').checked ? 'on' : '');
        formData.append('include_timestamp', document.getElementById('include-timestamp').checked ? 'on' : '');
        formData.append('title_prefix', document.querySelector('input[name="title_prefix"]').value);
        formData.append('footer_note', document.querySelector('input[name="footer_note"]').value);
        
        fetch('{% url "assets:label_template_create" %}', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const modal = bootstrap.Modal.getInstance(document.getElementById('saveTemplateModal'));
                modal.hide();
                showMessage('success', '模板保存成功');
                
                // 重新加载页面以更新模板列表
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                showMessage('error', data.error || '保存模板失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showMessage('error', '保存模板时发生错误');
        });
    }
    
    // 更新尺寸选择UI
    function updateSizeSelection() {
        const sizeOptions = document.querySelectorAll('.size-option');
        sizeOptions.forEach(option => {
            option.classList.remove('selected');
            const radio = option.querySelector('input[type="radio"]');
            if (radio.checked) {
                option.classList.add('selected');
            }
        });
    }
    
    // 更新布局选择UI
    function updateLayoutSelection() {
        const layoutOptions = document.querySelectorAll('.layout-option');
        layoutOptions.forEach(option => {
            option.classList.remove('selected');
            const radio = option.querySelector('input[type="radio"]');
            if (radio && radio.checked) {
                option.classList.add('selected');
            }
        });
    }
    
    // 显示消息
    function showMessage(type, message) {
        // 创建消息元素
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        // 插入到页面顶部
        const container = document.querySelector('.container-fluid');
        container.insertBefore(alertDiv, container.firstChild);
        
        // 自动消失
        setTimeout(() => {
            alertDiv.remove();
        }, 5000);
    }
    
    // 初始化
    updatePreview();
    updateEstimatedPages();
});
</script>
{% endblock %}